# @Time    :2021/12/10 上午 09:37
# @Author  :Mr Luo
# @File    :signals.py

from django.db.models.signals import post_save
from django.dispatch import receiver
from django.http import JsonResponse

from jiguang.models import Article
# app_key和master_secret定义在setting.py中，在极光网上申请
from dome_jg_py.settings import app_key, master_secret

import jpush

_jpush = jpush.JPush(app_key, master_secret)
_jpush.set_logging('INFO')


@receiver(post_save, sender=Article, dispatch_uid="article_created")
def create_article(sender, instance=None, created=False, **kwargs):
    response = {}
    if created:
        try:
            article_create_notification(instance.title, instance.content)
        except Exception as e:
            response['msg'] = str(e)
            return JsonResponse(response)


def article_create_notification(title, article_content):
    regid = '170976fa8a48d8864c2'
    push = _jpush.create_push()
    # 推送方式jpush.all_:广播，jpush.registration_id('170976fa8a48d8864c2'):一台设备，也可以是一个数组，jpush.
    # push.audience = jpush.registration_id(regid)
    # push.audience = jpush.audience.all_
    push.audience = jpush.alias('MrLuo')
    push.platform = jpush.all_

    ios = jpush.ios(alert='Hello, IOS JPush!', sound='a.caf', extras={'k1': 'v1'})
    android = jpush.android(title=title, alert=article_content, priority=1, style=1, alert_type=1)

    push.notification = jpush.notification(alert="Hello, JPush!", android=android, ios=ios)

    push.send()
